package com.github.davidfantasy.mybatisplus.generatorui;

import com.github.davidfantasy.mybatisplus.generatorui.configurer.GeneratorConfig;
import com.github.davidfantasy.mybatisplus.generatorui.configurer.MybatisPlusToolsApplication;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.FileSystemResource;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.function.Function;

@Slf4j
public class App {

    static String configFileName = "pui.yml";

    static Function<PropertySource,String> userName = p->String.valueOf(p.getProperty("username"));
    static Function<PropertySource,String> password = p->String.valueOf(p.getProperty("password"));
    static Function<PropertySource,String> driver = p->String.valueOf(p.getProperty("driver"));
    static Function<PropertySource,String> jdbcUrl = p->String.valueOf(p.getProperty("jdbcUrl"));
    static Function<PropertySource,String> basePackage = p->String.valueOf(p.getProperty("basePackage"));


    public static void main(String[] args) throws IOException {



        YamlPropertySourceLoader yamlPropertySourceLoader = new YamlPropertySourceLoader();

        //获取当前目录
        String currentPath = System.getProperty("user.dir");
        FileSystemResource fileSystemResource = new FileSystemResource(currentPath + File.separator + configFileName);
        log.info("start load `pui.yml` file at path {}",fileSystemResource.getPath());
        if(!fileSystemResource.exists()){
            log.error("not fount config file at project dir,Consider adding a `pui.yml` to your project, exit!");
            return;
        }
        List<PropertySource<?>> load = yamlPropertySourceLoader.load(fileSystemResource.getFilename(), fileSystemResource);
        PropertySource<?> propertySource = load.get(0);

        int port = 8063;
        if(args.length!=0){
            port = Integer.parseInt(args[0]);
        }
        GeneratorConfig config = GeneratorConfig.builder()
                .jdbcUrl(jdbcUrl.apply(propertySource))
                .userName(userName.apply(propertySource))
                .password(password.apply(propertySource))
                .port(port)
                .driverClassName(driver.apply(propertySource))
                .basePackage(basePackage.apply(propertySource))
                .build();
        MybatisPlusToolsApplication.run(config);
    }

}
